package com.zhangkunhao.notes.utils;

import com.zhangkunhao.notes.pool.PooledConnection;
import com.zhangkunhao.notes.exception.DbCloseException;
import com.zhangkunhao.notes.pool.MyPoolImpl;

import java.sql.SQLException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 使连接池扩容后恢复初始容量的工具类
 *
 * @author 20642
 * @description TODO
 * @date 2023/4/5 21:24
 */
public class DBUtils {
    public static void myClose(CopyOnWriteArrayList<PooledConnection> pooledConnections) throws DbCloseException {
        System.out.println("未关闭多余连接前连接池可用连接的容量：" + MyPoolImpl.pooledConnections.size());

        //倒序遍历，防止下标越界，也可以使用iterator遍历(暂时有bug)
        for (int i = pooledConnections.size() - 1; i > 9; i--) {
            if (pooledConnections.get(i).isBusy() == false) {
                try {
                    pooledConnections.get(i).getConnection().close();
                    pooledConnections.remove(i);
                } catch (SQLException e) {
                    throw new DbCloseException("连接池关闭连接出现异常了");
                }
            }
        }

        System.out.println("缩容关闭多余连接后，连接池目前可用连接的容量：" + MyPoolImpl.pooledConnections.size());
    }
}
